package com.polaris.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.widget.NestedScrollView
import java.lang.Math.abs

/**
 * CustomNestedScrollView  viewPager2嵌套viewPager2 里的recyclerView滑动，在RecyclerView外层套一个他帮助滑动优化
 *
 * @author Created by 半仙 on 2024/11/15/015 20:20
 */
class CustomNestedScrollView(context: Context, attrs: AttributeSet? = null) : NestedScrollView(context, attrs) {

    private var mDownX = 0f
    private var mDownY = 0f
    private val MIN_VERTICAL_ANGLE = 30 // 竖直滑动最小角度（单位：度）
    private val MAX_VERTICAL_ANGLE = 130 // 竖直滑动最大角度（单位：度）

    init {
        isFillViewport = true//是否将子视图宽高填满
    }

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                mDownX = ev.x
                mDownY = ev.y
            }

            MotionEvent.ACTION_MOVE -> {
                val moveX = ev.x
                val moveY = ev.y
                val deltaX = abs(moveX - mDownX)
                val deltaY = abs(moveY - mDownY)

                val angle = calculateAngle(deltaX, deltaY)

                // 判断滑动方向并且根据角度范围决定是否拦截
                val isVertical = deltaY > (deltaX - 30)

                if (isVertical) {
                    //竖直滑动：判断角度是否在允许的范围内
                    if (angle >= MIN_VERTICAL_ANGLE && angle <= MAX_VERTICAL_ANGLE) {
                        parent.requestDisallowInterceptTouchEvent(true)
                        return super.onInterceptTouchEvent(ev) // 允许竖直滑动
                    } else {
                        return false // 拦截非竖直滑动
                    }
                }
            }
        }
        return super.onInterceptTouchEvent(ev)
    }

    private fun calculateAngle(deltaX: Float, deltaY: Float): Float {
        // 使用 atan2 计算滑动的角度，返回的是从水平线到滑动向量的角度（单位：度）
        val angle = Math.atan2(deltaY.toDouble(), deltaX.toDouble()) * (180 / Math.PI)
        return angle.toFloat()
    }
}
